/*
 * @Author: soso
 * @Date: 2022-02-09 16:15:31
 * @LastEditTime: 2022-03-09 10:56:15
 * @LastEditors: Please set LastEditors
 * @Description: 监控配置文件
 * @FilePath: /go-mesh-sync/config/watch.go
 */

package config

import (
	"context"
	"log"

	"github.com/fsnotify/fsnotify"
)

type Watch struct {
	pathConfig string
	pathNodes  string
	watch      *fsnotify.Watcher
}

func NewConfsWatch(pathc, pathn string) (watch *Watch, err error) {
	watch = &Watch{}
	watch.watch, err = fsnotify.NewWatcher()
	if err != nil {
		return nil, err
	}

	watch.pathConfig = pathc
	watch.pathNodes = pathn
	return watch, nil
}

//监控目录
func (w *Watch) WatchConfs(ctx context.Context, cbfunc func(act fsnotify.Op, filePath string)) {
	w.watch.Add(w.pathConfig)
	w.watch.Add(w.pathNodes)

	go func() {
		for {
			select {
			case <-ctx.Done():
				return
			case ev := <-w.watch.Events:
				{
					if ev.Op&fsnotify.Write == fsnotify.Write {
						if cbfunc != nil {
							cbfunc(fsnotify.Write, ev.Name)
						}
					}
					// if ev.Op&fsnotify.Remove == fsnotify.Remove {
					// 	if cbfunc != nil {
					// 		cbfunc(fsnotify.Remove, ev.Name)
					// 	}
					// }
					// if ev.Op&fsnotify.Rename == fsnotify.Rename {
					// 	if cbfunc != nil {
					// 		cbfunc(fsnotify.Rename, ev.Name)
					// 	}
					// }
					// if ev.Op&fsnotify.Chmod == fsnotify.Chmod {
					// 	if cbfunc != nil {
					// 		cbfunc(fsnotify.Chmod, ev.Name)
					// 	}
					// }
				}
			case err := <-w.watch.Errors:
				{
					log.Println("watch error : ", err)
					return
				}
			}
		}
	}()
}

func (w *Watch) Close() {
	w.watch.Close()
}
